<template>
	<div :class="['message-input', !isPC && 'message-input-h5']">
		<div class="flex-row" >
			<MessageInputAudio v-if="isAudioEnable" :class="[
          'message-input-audio',
          isWeChat && 'message-input-wx-audio',
          isFunctionShow('audio') && 'message-input-wx-audio-open',
        ]" :isAudioMainShow="isFunctionShow('audio')" @switchAudio="switchAudio"></MessageInputAudio>
			<MessageInputEditor v-show="!isFunctionShow('audio')" class="message-input-editor" ref="editor"
				:placeholder="props.placeholder" :isMuted="props.isMuted" :muteText="props.muteText"
				:enableInput="props.enableInput" :enableAt="props.enableAt" :enableTyping="props.enableTyping"
				:isGroup="isGroup" @sendMessage="sendMessage" @onTyping="onTyping" @onAt="onAt" @onFocus="onFocus">
			</MessageInputEditor>
			<MessageInputAt v-if="props.enableAt" ref="messageInputAtRef" @insertAt="insertAt"
				@onAtListOpen="onAtListOpen"></MessageInputAt>
			<div class="message-input-emoji" @click="switchEmojiAndFeature('emoji')">
				<Icon :file="faceIcon" class="icon icon-face"></Icon>
			</div>
			<!-- <div class="message-input-more" @click="switchEmojiAndFeature('more')">
				<Icon :file="moreIcon" class="icon icon-more"></Icon>
			</div> -->
		</div>

		<!-- TODO 自己添加 -->
		<view class="bottom">
			<view class="bottom-item" @click="chooseImage('camera')">
				<image :src="getImageUrl('chat_camera.png')" style="width: 50rpx; height: 50rpx;"></image>
			</view>
			<view class="bottom-item" @click="chooseImage('album')">
				<image :src="getImageUrl('chat_album.png')" style="width: 50rpx; height: 50rpx;"></image>
			</view>
			<!-- <view class="bottom-item" @click="call(2)" v-if="!online">
				<image :src="getImageUrl('chat_vedio.png')" style="width: 50rpx; height: 50rpx;"></image>
			</view>
			<view class="bottom-item" @click="call(1)" v-if="!online">
				<image :src="getImageUrl('chat_audio.png')" style="width: 50rpx; height: 50rpx;"></image>
			</view> -->
		</view>
		<!-- TODO 自己添加 -->

		<div>
			<MessageQuote :style="{minWidth: 0}" :currentFunction="currentFunction" />
			<div class="message-input-emoji-picker" v-show="isFunctionShow('emoji')">
				<EmojiPickerDialog @insertEmoji="insertEmoji" @sendMessage="sendMessage"></EmojiPickerDialog>
			</div>
		</div>
	</div>
</template>
<script setup lang="ts">
	import TUIChatEngine, {
		TUIStore,
		StoreName,
		IConversationModel,
		TUIChatService,
	} from "@tencentcloud/chat-uikit-engine";
	import { ref, nextTick } from "../../../adapter-vue";
	import MessageInputEditor from "./message-input-editor.vue";
	import MessageInputAt from "./message-input-at/index.vue";
	import MessageInputAudio from "./message-input-audio.vue";
	import EmojiPickerDialog from "../message-input-toolbar/emoji-picker/emoji-picker-dialog.vue";
	import MessageQuote from "./message-input-quote/index.vue";
	import Icon from "../../common/Icon.vue";
	import faceIcon from "../../../assets/icon/face-uni.png";
	import moreIcon from "../../../assets/icon/more-uni.png";
	import { isPC, isH5, isWeChat, isApp } from "../../../utils/env";
	import { sendMessages, sendTyping } from "../utils/sendMessage";
	import TencentCloudChat from '@tencentcloud/chat';

	const props = defineProps({
		placeholder: {
			type: String,
			default: "this is placeholder",
		},
		replyOrReference: {
			type: Object,
			default: () => ({}),
			required: false,
		},
		isMuted: {
			type: Boolean,
			default: true,
		},
		muteText: {
			type: String,
			default: "",
		},
		enableInput: {
			type: Boolean,
			default: true,
		},
		enableAt: {
			type: Boolean,
			default: true,
		},
		enableTyping: {
			type: Boolean,
			default: true,
		},
	});

	const emit = defineEmits([
		"sendMessage",
		"resetReplyOrReference",
		"onTyping",
		"handleToolbarListShow",
	]);
	const replyOrReference = ref();
	const editor = ref();
	const messageInputAtRef = ref();
	const currentConversation = ref<IConversationModel>();
	const isAudioEnable = ref(isWeChat || isApp);
	const currentFunction = ref<string>("");
	const isGroup = ref<boolean>(false);

	TUIStore.watch(StoreName.CONV, {
		currentConversation: (conversation : IConversationModel) => {
			currentConversation.value = conversation;
			isGroup.value =
				currentConversation?.value?.type === TUIChatEngine.TYPES.CONV_GROUP;
		},
	});

	const switchAudio = (isAudioShow : boolean) => {
		if (isAudioShow) {
			switchEmojiAndFeature("audio");
		} else {
			switchEmojiAndFeature("");
		}
	};

	const switchEmojiAndFeature = (funcName : string) => {
		if (currentFunction.value === 'emoji') {
			if (funcName === 'emoji') {
				currentFunction.value = "";
			} else {
				currentFunction.value = funcName;
			}
			if (funcName === 'more') {
				nextTick(() => {
					emit("handleToolbarListShow");
				});
			}
		} else if (currentFunction.value === 'more') {
			emit("handleToolbarListShow");
			if (funcName === 'more') {
				currentFunction.value = "";
			} else {
				nextTick(() => {
					currentFunction.value = funcName;
				});
			}
		} else {
			currentFunction.value = funcName;
			if (funcName === 'more') {
				emit("handleToolbarListShow");
			}
		}
	};

	const isFunctionShow = (funcName : string) => {
		if (currentFunction.value === funcName) {
			return true;
		}
		return false;
	};

	const onTyping = (inputContentEmpty : boolean, inputBlur : boolean) => {
		sendTyping(inputContentEmpty, inputBlur);
	};

	const onAt = (show : boolean) => {
		messageInputAtRef?.value?.toggleAtList(show);
	};

	const onFocus = (keyboardHeight ?: number) => {
		if (isH5) {
			switchEmojiAndFeature("");
		}
	};

	const resetReplyOrReference = () => {
		console.warn("resetReplyOrReference");
	};

	const sendMessage = () => {
		let messageList;
		if (editor?.value?.getEditorContent) {
			messageList = editor?.value?.getEditorContent();
		}
		sendText(messageList);
	};

	const insertEmoji = (emoji : any) => {
		editor?.value?.addEmoji && editor?.value?.addEmoji(emoji);
	};

	const insertAt = (atInfo : any) => {
		editor?.value?.insertAt && editor?.value?.insertAt(atInfo);
	};

	const onAtListOpen = () => {
		editor?.value?.blur && editor?.value?.blur();
	};

	// 消息撤回后重新编辑
	const reEdit = (content : any) => {
		editor?.value?.resetEditor();
		resetReplyOrReference();
		editor?.value?.setEditorContent(content);
	};

	defineExpose({
		insertEmoji,
		reEdit,
	});


	//TODO 以下自己添加的
	// import common from '@/common/common.js'
	import { ossUpload, getFileName } from '@/js_sdk/jason-alioss-upload/oss.js'
	const online = ref<boolean>(uni.$constant.online);
	const sendText = (messageList : any) => {
		if (uni.$constant.online) {
			editor?.value?.resetEditor && editor?.value?.resetEditor();
			resetReplyOrReference();
			sendMessages(messageList, currentConversation.value);
			emit("sendMessage");
			return
		}

		// [{"type":"text","payload":{"text":"gg"}}]
		let content = messageList[0].payload.text;
		let param = { type: "1", otherTxCode: getApp().globalData.chatTxCode, text: content};
		requestFee(param).then((res)=>{
			editor?.value?.resetEditor && editor?.value?.resetEditor();
			resetReplyOrReference();
			sendMessages(messageList, currentConversation.value);
			emit("sendMessage");
		})
	}
	
	const requestFee = (param:any)=> {
		return new Promise((resolve, reject)=>{
			uni.$http.chatFee(param).then(res=>{
				resolve(res)
			}).catch(res=>{
				uni.hideKeyboard();
				uni.$emit('openVip')
			})
		})
	}
	
	const chooseImage = (sourceType : String) => {
		uni.chooseImage({
			count: 1,
			mediaType: ['image'], // 图片
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: [sourceType], // album;camera
			success: async(file) => {
				const options = {
					to: `` + getApp().globalData.chatTxCode,
					conversationType: TencentCloudChat.TYPES.CONV_C2C,
					payload: {
						file: file,
					},
					needReadReceipt: true,
				} as SendMessageParams;
				
				if (uni.$constant.online) {
					TUIChatService.sendImageMessage(options);
				} else {
					uploadOOS(file, options);
				}
			}
		});
	}
	
	const uploadOOS = async (file, options)=>{
		let dir = 'im';
		let fileName = getFileName(file.tempFilePaths[0]);
		const { success, data } = await ossUpload(file.tempFilePaths[0], fileName, dir)
		if(success){
			let param = { type: '1', otherTxCode: getApp().globalData.chatTxCode, text: data};
			requestFee(param).then((res)=>{
				TUIChatService.sendImageMessage(options);
			})
		}
	}

	const call = async (type) => {
		const options = {
			userID: getApp().globalData.chatTxCode,
			callMediaType: type, // 语音通话(callMediaType = 1)、视频通话(callMediaType = 2)
		};
		// uni.$TUICallKit.call(options, (res) => {
		// 	if (res.code === 0) {
		// 		console.log('音视频拨打成功');
		// 	} else {
		// 		console.log(`音视频拨打失败, error message = ${res.msg}`);
		// 	}
		// });
	}
	
</script>

<style scoped lang="scss">
	@import url("../../../assets/styles/common.scss");

	.message-input {
		position: relative;
		display: flex;
		flex-direction: column;
		border: none;
		height: 100%;
		width: 100%;
		max-height: 100%;
		max-width: 100%;
		overflow: hidden;
		background: #ebf0f6;

		&-editor {
			flex: 1;
			display: flex;
		}

		&-button {
			width: fit-content;
		}

		.icon {
			width: 23px;
			height: 23px;

			&-face {
				margin: 7px;
			}

			&-more {
				margin: 7px 0px;
			}
		}

		&-wx {
			&-audio {
				&-open {
					flex: 1;
				}
			}
		}

		&-emoji-picker {
			padding-top: 10px;
		}
	}

	.message-input-h5 {
		display: flex;
		flex-direction: column;
		height: calc(100% - 20px);
		width: calc(100% - 20px);
		max-height: 100%;
		max-width: calc(100% - 20px);
		padding: 10px;
		overflow: hidden;
	}

	.flex-row {
		display: flex;
		flex-direction: row;
	}

	.bottom {
		display: flex;
		flex-direction: row;
		width: 100%;
		height: 80rpx;
		box-sizing: border-box;
		align-items: center;

		.bottom-item {
			flex: 1;
			display: flex;
			flex-direction: row;
			justify-content: center;

			u-icon {
				margin: auto;
			}
		}
	}
</style>